#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

#include "log.hpp"  //日志信息
#include "Protocol.hpp"

#define NUM 1024

namespace Client
{
    // using namespace std;
    class calClient
    {
    public:
        calClient(const string& serverip,const uint16_t serverport)
            :_sock(-1),_serverip(serverip),_serverport(serverport)
        {}
        void ininClinet()
        {
            //1.创建socket
            _sock = socket(AF_INET,SOCK_STREAM,0);
            if(_sock < 0)
            {
                logMessage(FATAL,"socket create error");//错误日志信息
                exit(2);
            }
            //2.tcp客户端也要bind，但是不用我们显示的bind，OS会帮我们bind的

        }
        void start()
        {

            struct sockaddr_in server;
            memset(&server,0,sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(_serverport);
            server.sin_addr.s_addr = inet_addr(_serverip.c_str());
            //向服务器发起链接请求
            if(connect(_sock,(struct sockaddr*)&server,sizeof(server)) != 0)
            {
                logMessage(ERROR,"socket connect error");
            }
            else
            {
                string msg;
                string inbuffer;
                while(true)
                {
                    cout << "Mycal>> ";
                    getline(cin,msg);   //cin>> 1+1

                    //准备计算任务，
                    Request req = ParseLine(msg);   //计算任务结构化
                    string content;
                    if(!req.serialize(&content)) continue;   //"1 + 1" 序列化
                    string send_string = enLength(content); //"content_len"\r\n"x op y"\r\n 添加报头

                    // 发送计算任务
                    send(_sock,send_string.c_str(),send_string.size(),0);

                    // 获取计算结果
                    string package,text;
                    if(!recvPackage(_sock,inbuffer,&package)) // 获取一个完整的响应"content_len"\r\n"exitcode result"\r\n
                        continue;
                    if(!deLength(package,&text))    //"exitcode result" 去报头
                        continue;
                    Response resp;
                    resp.deserialize(text);         //反序列化

                    // 输出计算结果
                    cout << "exitcode: " <<resp._exitcode << endl;
                    cout << "result: " <<resp._result << endl << endl;

                }
            }
        }
        // 简易版本的状态机，用于拆分输入的计算字符串
        Request ParseLine(const string& line)
        {
            // "1+1" "10*10" "1234/0"
            int status = 0;
            int i = 0,cnt = line.size();
            string x,y;
            char op;
            while(i < cnt)
            {
                switch(status)
                {
                    case 0:
                    {
                        if(!isdigit(line[i]))
                        {
                            op = line[i];
                            status = 1;
                        }
                        else 
                            x.push_back(line[i++]);
                    }
                        break;
                    case 1:
                    {
                        i++;
                        status = 2;
                    }
                        break;
                    case 2:
                        y.push_back(line[i++]);
                        break; 
                }
            }
            return Request(stoi(x),stoi(y),op);
        }
        ~calClient()
        {
            if(_sock >= 0) close(_sock);//可写，可不写
        }
    private:
        int _sock;
        string _serverip;
        uint16_t _serverport;
    };

}//namespace Client end